<?php

class myAcicrud extends Acicrud {
    public function __construct($table = null, $database = null) {
        parent::__construct($table, $database);
        $this->loger = new Acicrud('logs');
        $this->actionTypes = array('create' => '1', 'read' => '2', 'update' => '3', 'delete' => '4');
        $this->user = $this->session->all_userdata();
        $this->user = $this->user['ip_address'];
    }
    
    public function create($o) {
        $result = parent::create($o);
        $obj = null;
        if($result != 0)
            $obj = parent::readLast();
        else
            $obj = $o;
        $this->logCreate($obj);
        return $result;
    }
    
    public function delete($where) {
        $obj = parent::read($where);
        $this->logDelete($obj);
        $result = parent::delete($where);
        return $result;
    }
    
    public function update($o) {
        $result = parent::update($o);
        $this->logUpdate($o);
        return $result;
    }
    
    public function deleteAll($id, $row) {
        $obj = parent::getAll(null, null, array($row => $id));
        foreach($obj as $val){
            $this->logDelete($val);
        }
        $result = parent::deleteAll($id, $row);
        return $result;
    }

    ////////////////////////////////////////////////////
    
    protected function logCreate($dbObject) {
        $this->log('create', $dbObject);
    }
    
    protected function logRead($dbObject) {
        $this->log('read', $dbObject);
    }
    
    protected function logUpdate($dbObject) {
        $this->log('update', $dbObject);
    }
    
    protected function logDelete($dbObject) {
        $this->log('delete', $dbObject);
    }
    
    protected function log($actionType, $dbObject) {
        $o = new stdClass();
        $o->user = $this->user;
        $o->table = $this->table;
        $comment = "";
        foreach($this->fields as $key => $value){
            if(isset($dbObject->$key))
                $comment .= "[" . $key . "] => '" . $dbObject->$key. "', ";
        }
        $o->comment = $comment;
        $o->fk_action_type = $this->actionTypes[$actionType];
        $this->loger->create($o);
    }
    
}

?>
